package com.hxzy.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.util.MarketingThreadLocalUtil;
import com.hxzy.controller.mobile.product.req.MobileProductReq;
import com.hxzy.controller.mobile.product.resp.MobileProductResp;
import com.hxzy.controller.vue.login.resp.AdminLoginResp;
import com.hxzy.controller.vue.mapstruct.ProductConvert;
import com.hxzy.controller.vue.product.dto.DishFlavorItem;
import com.hxzy.controller.vue.product.dto.DishFlavorProperty;
import com.hxzy.controller.vue.product.req.BatchUpOrDownReq;
import com.hxzy.controller.vue.product.req.ProductAddReq;
import com.hxzy.controller.vue.product.req.ProductEditReq;
import com.hxzy.controller.vue.product.req.ProductReq;
import com.hxzy.controller.vue.product.resp.ProductResp;
import com.hxzy.entity.DishFlavor;
import com.hxzy.entity.Product;
import com.hxzy.service.DishFlavorService;
import com.hxzy.service.ProductService;
import com.hxzy.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
* @author 11452
* @description 针对表【product(商品信息)】的数据库操作Service实现
* @createDate 2023-08-28 11:54:55
*/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements ProductService{


    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 分页查询
     * @param req
     * @return
     */
    @Override
    public PageInfo<ProductResp> search(ProductReq req) {
        return PageHelper.startPage(req.getPage(),req.getSize())
                .doSelectPageInfo(()->{
                   List<ProductResp> list= baseMapper.search(req);
                   //继续查询它是否拥有口味列表
                    for(ProductResp  p : list){
                        List<DishFlavorProperty> dishFlavorPropertyList=dishFlavorService.dishFlavorsByPrdouctId(p.getId());
                        p.setDishFlavors(dishFlavorPropertyList);
                    }
                });
    }

    /**
     * 新增商品
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean add(ProductAddReq req) {
        AdminLoginResp  adminLoginResp= MarketingThreadLocalUtil.adminThreadLocal.get();

        Product entity = ProductConvert.INSTANCE.convert(req);
        entity.setMerchantId(adminLoginResp.getId());
        entity.setScore(5);
        //保存
        boolean save = this.save(entity);
        if(save){
            //判断是否有口味信息
            List<DishFlavorProperty> dishFlavors = req.getDishFlavors();
            for(DishFlavorProperty dfp : dishFlavors){

                DishFlavor  dishFlavor=new DishFlavor();
                //商品ID
                dishFlavor.setDishId(entity.getId());
                dishFlavor.setName(dfp.getName());
                dishFlavor.setIsDeleted("0");
                String jsonStr= JSONUtil.toJsonStr(dfp.getValue());
                dishFlavor.setValue(jsonStr);
                //保存
                this.dishFlavorService.save(dishFlavor);
            }
        }
        return save;
    }

    @Override
    public ProductResp findById(Long id) {
        AdminLoginResp adminLoginResp=MarketingThreadLocalUtil.adminThreadLocal.get();
        Product db = this.getById(id);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }
        if(!db.getMerchantId().equals(adminLoginResp.getId())){
            throw new ServiceException(AckCode.PERMISSION_NOT_ACCESS_CATEGORY);
        }
        ProductResp resp=ProductConvert.INSTANCE.convert(db);
        //查询商品口味信息
        List<DishFlavorProperty> dishFlavorPropertyList = this.dishFlavorService.dishFlavorsByPrdouctId(resp.getId());
        resp.setDishFlavors(dishFlavorPropertyList);
        return resp;
    }

    /**
     * 修改
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean edit(ProductEditReq req) {
        AdminLoginResp adminLoginResp=MarketingThreadLocalUtil.adminThreadLocal.get();
        Product db = this.getById(req.getId());
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }
        if(!db.getMerchantId().equals(adminLoginResp.getId())){
            throw new ServiceException(AckCode.PERMISSION_NOT_ACCESS_CATEGORY);
        }

        Product convert = ProductConvert.INSTANCE.convert(req);
        boolean success = this.updateById(convert);
        if(success){
            //先删删除原先口味数据
            LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId,req.getId());
            this.dishFlavorService.remove(queryWrapper);

            //判断是否有口味信息
            List<DishFlavorProperty> dishFlavors = req.getDishFlavors();
            for(DishFlavorProperty dfp : dishFlavors){

                DishFlavor  dishFlavor=new DishFlavor();
                //商品ID
                dishFlavor.setDishId(req.getId());
                dishFlavor.setName(dfp.getName());
                dishFlavor.setIsDeleted("0");
                String jsonStr= JSONUtil.toJsonStr(dfp.getValue());
                dishFlavor.setValue(jsonStr);
                //保存
                this.dishFlavorService.save(dishFlavor);
            }
        }

        return success;
    }

    /**
     * 批量上下架商品
     * @param req
     * @return
     */
    @Override
    public boolean batchUpOrDown(BatchUpOrDownReq req) {
        AdminLoginResp adminLoginResp = MarketingThreadLocalUtil.adminThreadLocal.get();
        //查询所选的产品是不是本商家的
        LambdaQueryWrapper<Product> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.ne(Product::getMerchantId,adminLoginResp.getId());
        queryWrapper.in(Product::getId,req.getIds());
        long count = this.count(queryWrapper);
        if(count>0){
            throw new ServiceException(AckCode.PERMISSION_NOT_ACCESS_CATEGORY);
        }

        long result=this.baseMapper.batchUpOrDown(req);
        return result>0;
    }

    @Override
    public List<MobileProductResp> mobileSearch(MobileProductReq req) {
        List<MobileProductResp> mobileProductResps = this.baseMapper.mobileSearch(req);
        //查询口味明细
        mobileProductResps.stream().forEach(p-> {

            //查询口味信息
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, p.getId());
            queryWrapper.eq(DishFlavor::getIsDeleted, "0");
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);

            //组装成自己定义的口味数据给前端
            List<DishFlavorProperty> propertyList = new ArrayList<>();


            dishFlavorList.stream().forEach(s -> {
                DishFlavorProperty property = new DishFlavorProperty();
                property.setName(s.getName());
                //json反序列化
                List<DishFlavorItem> dishFlavorItems = JSONUtil.toList(s.getValue(), DishFlavorItem.class);
                property.setValue(dishFlavorItems);
                propertyList.add(property);
            });

            //添加到商品
            p.setDishFlavors(propertyList);

        });

        return mobileProductResps;
    }

    /**
     * 根据主键查询商品信息（加锁）
     * @param dishId
     * @return
     */
    @Override
    public Product findbyIdLock(Long dishId) {
        return this.baseMapper.findByIdLock(dishId);
    }
}




